﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Robert MacLean">
//     This file is released under the LGPL. For more information see 
//     http://gallery2.codeplex.com.
//     Originally created by Robert MacLean http://www.sadev.co.za
// </copyright>
//-----------------------------------------------------------------------


namespace g2Export
{
    using System;
    using System.Collections.ObjectModel;
    using System.IO;
    using SADev.Gallery2.Protocol;

    class Program
    {
        static void Main(string[] args)
        {
            write(ConsoleColor.Cyan, "Welcome to the Gallery2 Exporter");
            write(ConsoleColor.Blue, "Server URL (example: http://www.mysite.com/gallery2):");
            string url = Console.ReadLine();

            write(ConsoleColor.Blue, @"Folder to Export to (example: c:\tmp\):");
            string targetFolder = Console.ReadLine();

            write(ConsoleColor.Blue, "Username:");
            string username = Console.ReadLine();
            write(ConsoleColor.Blue, "Password:");
            string password = Console.ReadLine();

            Actions g2Actions = new Actions(url);

            if (g2Actions.NoOp().Status != 0)
            {
                throw new Exception("No-op failed!");
            }

            string AuthToken = g2Actions.LogOn(username, password).AuthToken;

            Collection<Album> albums = g2Actions.FetchAlbumsPrune(AuthToken).Albums;
            foreach (Album album in albums)
            {
                string albumFolder = targetFolder + album.Title;
                if (!Directory.Exists(albumFolder))
                {
                    Directory.CreateDirectory(albumFolder);
                }

                Collection<Image> images = g2Actions.FetchImages(AuthToken, album.Name).Images;
                foreach (Image image in images)
                {
                    write(ConsoleColor.Gray, String.Format("Starting download of {0} \\ {1}", album.Name, image.Title));
                    g2Actions.DownloadRawImage(image, String.Format("{0}\\{1}", albumFolder, image.Title));
                    write(ConsoleColor.DarkCyan, String.Format("Download complete for {0} \\ {1}", album.Name, image.Title));
                }
            }

            Console.WriteLine("Done :)");
        }

        private static void write(ConsoleColor colour, string message)
        {
            ConsoleColor original = Console.ForegroundColor;
            Console.ForegroundColor = colour;
            Console.WriteLine(message);
            Console.ForegroundColor = original;
        }
    }
}
